export namespace StrUtils {
    export function getNameFromUrl(url: string) {
        return url.split('/').pop() || 'img.jpg';
    }

    export function queryToString(query: any) {
        if (!query) {
            return ''
        }
        if (typeof query !== 'object') {
            return ''
        }
        return Object.keys(query).map(key => {
            if (query[key] === null || query[key] === '' || query[key] === undefined || query[key] === 'undefined') {
                return ''
            }
            if (typeof query[key] === 'object' && query[key]?.length) {
                return `${key}=${JSON.stringify(query[key])}`
            }
            return `${key}=${query[key]}`
        }).filter(item => item.trim() !== '').join('&')
    }

    export function parseGM_Metadata(scriptText: string) {
        const metadata: { [key: string]: string } = {};
        const lines = scriptText.split('\n');
        let inMetadata = false;
        for (const line of lines) {
            if (/\/\/\s==UserScript==\r?/.test(line) || /\/\/\s==\/UserScript==\r?/.test(line)) {
                inMetadata = !inMetadata;
            } else if (inMetadata) {
                const keyReg = /\/\/\s?@[:?a-zA-Z0-9_-]+/
                const key = line.match(keyReg)?.[0]?.replace('//', '').replace('@', '').trim();
                if (!key) {
                    continue
                }
                const value = line.replace(keyReg, '').trim()

                if (metadata[key] === undefined) {
                    metadata[key] = value
                } else {
                    metadata[key] += ',' + value
                }
            }
        }

        return metadata;
    }

    export function getRandomString(length: number = 16) {
        const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-';
        let result = '';
        for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
        return result;
    }

    export function stringToUnsignedInts(str: string) {
        let result = [];
        for (let i = 0; i < str.length; i++) {
            let codePoint = str.codePointAt(i);
            result.push((codePoint || 1) >>> 0);
        }
        return result;
    }

    export function base64ToArrayBuffer(base64: string) {
        const binaryStr = atob(base64);
        const buffer = new ArrayBuffer(binaryStr.length);
        const view = new Uint8Array(buffer);
        for (let i = 0; i < binaryStr.length; i++) {
            view[i] = binaryStr.charCodeAt(i);
        }
        return buffer;
    }

    export function arrayBufferToBase64(buffer: ArrayBuffer) {
        const uint8Array = new Uint8Array(buffer);
        let binaryStr = '';
        uint8Array.forEach(byte => {
            binaryStr += String.fromCharCode(byte);
        });
        return btoa(binaryStr);
    }

}